package com.luban.producer.service.listener;

import com.alibaba.fastjson.JSON;
import com.luban.producer.service.TestService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

import java.util.Map;

/**
 * 需要视频资料或咨询课程的同学可以添加若曦老师的QQ:2746251334
 */
@RocketMQTransactionListener
public class TransactionListener  implements RocketMQLocalTransactionListener{


    @Autowired
    TestService testService;

    //执行本地事务
//    @Transactional
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            System.out.println("开始执行事务");
            //调用多个事务 并且是异步情况  就要用挂起
            return testService.insert(message);
        }catch (Exception e){
            System.out.println("本地事务回滚");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }


    //事务回调
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        Map map = JSON.parseObject(new String((byte[]) message.getPayload()), Map.class);
        if (testService.checkTransaction(String.valueOf(map.get("id")))>0) {
            System.out.println("事务回调提交");
            return RocketMQLocalTransactionState.COMMIT;
        }
        System.out.println("事务回调回滚");
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
